//
//  MILLightsSettingViewController.m
//  MicrowaveInteractionLight
//
//  Created by maple on 2016/12/15.
//  Copyright © 2016年 maple. All rights reserved.
//

#import "MILLightsSettingViewController.h"
#import "MILLightSettingCollectionViewCell.h"
#import "MILSelectedWiFiViewController.h"
#import "GetUserDeviceApi.h"
#import "SettingSwitchApi.h"
#import "UnBindDeviceApi.h"
#import "MILUserDeviceModel.h"
#import "DeviceCtrlVC_light.h"

@interface MILLightsSettingViewController ()<MILLightSettingVCDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;
//编辑模式
@property(nonatomic,assign)BOOL isEditMode;
/** 空数据提示 */
@property (nonatomic,strong) UILabel *emptyLabel;

@end

@implementation MILLightsSettingViewController
#pragma mark -- 懒加载
//设备列表
- (NSMutableArray *)myDataMutableArray
{
    if (!_myDataMutableArray)
    {
        _myDataMutableArray = [NSMutableArray array];
    }
    
    return _myDataMutableArray;
}

- (UILabel *)emptyLabel{
    
    if (!_emptyLabel) {
        _emptyLabel = [[UILabel alloc]init];
        _emptyLabel.text = @"暂无设备";
        _emptyLabel.font = [UIFont systemFontOfSize:15];
        _emptyLabel.textColor = [UIColor colorWithRed:151/255.0 green:151/255.0 blue:151/255.0 alpha:1];
        [self.view addSubview:_emptyLabel];
    }
    return _emptyLabel;
}

//- (void)dealloc
//{
//    [[NSNotificationCenter defaultCenter]removeObserver:self];
//}

#pragma mark -- UI
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //初始化UI
    [self initMILLightsSettingView];
    
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deviceStateChange:) name:@"DeviceStateNotification" object:nil];

}

//- (void)deviceStateChange:(NSNotification *)notify{
//    NSString *content = notify.object;
//    NSDictionary *dic = notify.userInfo;
//    if ([dic[@"backCode"] isEqualToString:@"1801"]){
//        NSString *string = [NSString string];
//        if (content.length == 10) {
//            string = [content substringWithRange:NSMakeRange(0, 2)];
//            for (MILUserDeviceModel *model in self.myDataMutableArray) {
//                if ([model.mac isEqualToString:dic[@"macAddress"]]) {
//                    if ([string isEqualToString:@"01"]) {
//                        model.is_open = @"1";
//                    } else {
//                        model.is_open = @"0";
//                    }
//                }
//            }
//            [SVProgressHUD showSuccessWithStatus:@"操作成功"];
//            [self.myCollectionView reloadData];
////            [self getUserDeviceList];
//        }
//    }
//    
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //获取设备列表
    [self getUserDeviceList];
}



- (void)refreshBaseControlValue
{
    [self setNavigationBarTitle:@"灯泡设置"];
    [self setRightButtonImage:[UIImage imageNamed:@"add"]];
    self.navigationBar.backgroundColor = [UIColor blackColor];
    [self setLeftButtonImage:[UIImage imageNamed:@"back_icon"]];
    
    
    if (self.myDataMutableArray.count == 0) {
        self.emptyLabel.hidden = NO;
    } else {
        self.emptyLabel.hidden = YES;
    }
}

//初始化UI
- (void)initMILLightsSettingView
{
    [self.emptyLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view);
    }];
    
    //注册
    [self.myCollectionView registerNib:[UINib nibWithNibName:@"MILLightSettingCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"MILLightSettingCollectionViewCell"];
}

- (void)onRightButtonClick:(UIButton *)sender
{
    if (self.isEditMode)
    {
        self.rightButton = nil;
        [self setRightButtonImage:[UIImage imageNamed:@"add"]];
        self.isEditMode = NO;
        [self.myCollectionView reloadData];
    }
    else
    {
        //添加设备界面
        MILSelectedWiFiViewController *milSelectedWiFiVC = [[MILSelectedWiFiViewController alloc]init];
        [self.navigationController pushViewController:milSelectedWiFiVC animated:YES];
    }
    
}

#pragma mark -- 获取设备列表
- (void)getUserDeviceList
{
    GetUserDeviceApi *api = [[GetUserDeviceApi alloc]init];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary * myDic = [request responseJSONObject];
        NSLog(@"my Dic == %@ ",myDic);
        if ([myDic[@"errcode"] intValue] == 0) {
            NSArray *returnDataArray = myDic[@"data"];
            [self.myDataMutableArray removeAllObjects];
            for (NSDictionary *dic in returnDataArray) {
                MILUserDeviceModel *model = [[MILUserDeviceModel alloc]init];
                model.ID = dic[@"id"];
                model.device_id = dic[@"device_id"];
                model.mac = dic[@"mac"];
                model.name = dic[@"name"];
                model.is_alert = dic[@"is_alert"];
                model.is_online = dic[@"is_online"];
                model.is_open = dic[@"is_open"];
                [self.myDataMutableArray addObject:model];
            }
            if (self.myDataMutableArray.count == 0) {
                self.emptyLabel.hidden = NO;
            } else {
                self.emptyLabel.hidden = YES;
            }
            // 查询设备近场在线状态
            for (MILUserDeviceModel *model in self.myDataMutableArray)
            {
                int i = [[DTCloudManager defaultJNI_iOS_SDK] getDevicesState:model.mac];
                if (i == 1)
                {
                    model.is_online = @"1";
                }
            }
            [self.myCollectionView reloadData];
        }else{
            [SVProgressHUD showErrorWithStatus:myDic[@"errmsg"]];
        }
        
        
    } failure:^(YTKBaseRequest *request) {
        
        [SVProgressHUD showErrorWithStatus:@"请求失败"];
    }];
    
}


#pragma mark -- UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.myDataMutableArray.count;
//    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MILLightSettingCollectionViewCell *cell= [collectionView dequeueReusableCellWithReuseIdentifier:@"MILLightSettingCollectionViewCell" forIndexPath:indexPath];
  
    MILUserDeviceModel *model = self.myDataMutableArray[indexPath.row];
    [cell.myDeviceNameLabel setTitle:model.name forState:UIControlStateNormal];
//    isopen
    if ([model.is_open isEqualToString:@"1"]) {
        cell.myLightImageView.image = [UIImage imageNamed:@"liangdeng"];
        [cell.myLightStatusBtn setBackgroundImage:[UIImage imageNamed:@"openLight"] forState:UIControlStateNormal];
        [cell.myLightStatusBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 15)];
        [cell.myLightStatusBtn setTitle:@"ON" forState:UIControlStateNormal];
    }
    else
    {
        cell.myLightImageView.image = [UIImage imageNamed:@"deng"];
        [cell.myLightStatusBtn setBackgroundImage:[UIImage imageNamed:@"closeLight"] forState:UIControlStateNormal];
        [cell.myLightStatusBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
        [cell.myLightStatusBtn setTitle:@"OFF" forState:UIControlStateNormal];
    }
    
    if ([model.is_online isEqualToString:@"1"]) {
        cell.wifStatusImageView.image = [UIImage imageNamed:@"icon_wifi_online"];
    } else {
        cell.wifStatusImageView.image = [UIImage imageNamed:@"icon_wifi_offline"];
    }
    cell.delegate = self;
    if (self.isEditMode)
    {
        cell.myDeleteDeviceBtn.hidden = NO;
    }
    else
    {
        cell.myDeleteDeviceBtn.hidden = YES;
    }
    //加长按手势
    UILongPressGestureRecognizer *ges = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longGesFuctionAction:)];
    cell.tag = indexPath.row;
    [cell addGestureRecognizer:ges];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MILUserDeviceModel *model = self.myDataMutableArray[indexPath.row];
    LightToningViewController *vc = [[LightToningViewController alloc] init];
    vc.deviceModel = model;
    [self.navigationController pushViewController:vc animated:YES];
    
    
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //此处设置item宽  左右以及中间间距 默认为10
    CGFloat x = ([UIScreen  mainScreen].bounds.size.width-75) /2.0;
    CGFloat y = x*150/120;
    return CGSizeMake(x, y);
}
//
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(25, 25, 25, 25);
}

#pragma mark -- 长按事件
- (void)longGesFuctionAction:(UILongPressGestureRecognizer *)ges
{
    if (!self.isEditMode)
    {
        if (ges.state == UIGestureRecognizerStateBegan) {
            
            self.isEditMode = YES;
            self.rightButton = nil;
            [self setRightButtonTitle:@"完成"];
            [self.myCollectionView reloadData];
        }
    }
    
}


#pragma mark -- MILLightSettingVCDelegate
- (void)changeLightDeviceStatusFunction:(UIButton *)btn
{
    //改变开关
    MILLightSettingCollectionViewCell * cell = nil;
    if ([btn isKindOfClass:[UIButton class]])
    {
        cell = (MILLightSettingCollectionViewCell *)[[btn superview] superview];
    }
    
    NSIndexPath *indexPath = [self.myCollectionView indexPathForCell:cell];
    MILUserDeviceModel *model = self.myDataMutableArray[indexPath.row];
    if ([model.is_open isEqualToString:@"1"])
    {
        btn.selected = NO;
    }
    else
    {
        btn.selected = YES;
    }
    model.is_open = [model.is_open isEqualToString:@"1"]?@"0":@"1";
//    NSString *string = [NSString stringWithFormat:@"0%@00001000",model.is_open];
//    int i = [[DTCloudManager defaultJNI_iOS_SDK]sendCommandByFunctionCode:@"1001" functionCommand:string deviceMacAddress:model.mac];
    
    SettingSwitchApi *api = [[SettingSwitchApi alloc]initWithDictionary:@{@"uid":EXRACT_OBJECT(UID),@"token":EXRACT_OBJECT(TOKEN),@"device_id":model.device_id,@"switch":model.is_open}];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary * myDic = [request responseJSONObject];
        NSLog(@"my Dic == %@ ",myDic);
        if ([myDic[@"errcode"] intValue] == 0) {
            [SVProgressHUD showSuccessWithStatus:@"操作成功"];
            [self getUserDeviceList];
        }else{
            [SVProgressHUD showErrorWithStatus:myDic[@"errmsg"]];
        }
        
        
    } failure:^(YTKBaseRequest *request) {
        
        [SVProgressHUD showErrorWithStatus:@"请求失败"];
    }];
}

- (void)deleteLightDeviceFunction:(UIButton *)btn
{
    [[AlertViewManager shareManager]initWithMessage:@"是否确认删除该设备？" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确认"] clickAtIndex:^(NSInteger buttonIndex, UIAlertView *alertView) {
        if (buttonIndex == 1) {
            //删除设备
            MILLightSettingCollectionViewCell * cell = nil;
            if ([btn isKindOfClass:[UIButton class]])
            {
                cell = (MILLightSettingCollectionViewCell *)[[btn superview] superview];
            }
            
            NSIndexPath *indexPath = [self.myCollectionView indexPathForCell:cell];
            MILUserDeviceModel *model = self.myDataMutableArray[indexPath.row];
            UnBindDeviceApi *api = [[UnBindDeviceApi alloc]initWithPar:@{@"id":model.ID}];
            [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                NSDictionary * myDic = [request responseJSONObject];
                NSLog(@"my Dic == %@ ",myDic);
                if ([myDic[@"errcode"] intValue] == 0) {
                    [SVProgressHUD showSuccessWithStatus:@"解绑设备成功"];
                    [self getUserDeviceList];
                }else{
                    [SVProgressHUD showErrorWithStatus:myDic[@"errmsg"]];
                }
                
                
            } failure:^(YTKBaseRequest *request) {
                
                [SVProgressHUD showErrorWithStatus:@"请求失败"];
            }];

        }
    }];
}
@end
